﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DispatchAssist.Model;
using DispatchAssist.Service;
using System.Web.Services.Protocols;
using System.Collections;


namespace DispatchAssist.AppHost
{
    public partial class frmManualSendSMSAlert : Form
    {
        #region Members

        SMSAlertAllInfo smsAlertInfo = new SMSAlertAllInfo();
        AuthService service = new AuthService();
        AlertMessageGetterService alertmassageservice = new AlertMessageGetterService();
        delegate void FunDelegate();

        Sunisoft.IrisSkin.SkinEngine skinEngine1;
        private readonly object locker = new object();

        #endregion

        #region Ctor.

        public frmManualSendSMSAlert()
        {
            InitializeComponent();
            skinEngine1 = SkinConfig.Instance.EnsureSkin(this);
        }

        public frmManualSendSMSAlert(SMSAlertAllInfo smsinfo)
            : this()
        {
            smsAlertInfo = smsinfo;
        }

        #endregion

        private void frmManualSendSMSAlert_Load(object sender, EventArgs e)
        {
            service.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();
            alertmassageservice.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();
            alertmassageservice.InsertSMSMsgModelCompleted += new InsertSMSMsgModelCompletedEventHandler(alertmassageservice_InsertSMSMsgModelCompleted);

        }

        private void BindAllBaseInfo()
        {

            List<string> al = new List<string>();
            al.Add(smsAlertInfo.GroupCode);
            BindContactGroups();
            SetCheckedItems(al);

            BindBaseInfoOfAlertMessage();

        }

        public void wjs()
        {
            FunDelegate funDelegate = new FunDelegate(BindAllBaseInfo);

            /*========================================================
             * 使用this.BeginInvoke方法
             * （也可以使用this.Invoke()方法）
            ========================================================*/

            // this.BeginInvoke(被调用的方法的委托，要传递的参数[Object数组])


            IAsyncResult aResult = funDelegate.BeginInvoke(callbackm, this);

            // 用于等待异步操作完成(-1表示无限期等待)
            //aResult.AsyncWaitHandle.WaitOne(0);

            //// 使用this.EndInvoke方法获得返回值
            //string str = (string)this.EndInvoke(aResult);
            //MessageBox.Show(str.ToString());
            //addPromptAlertControls();


        }

        private void callbackm(IAsyncResult result)
        {
            if (result.IsCompleted)
            {
                //dddd.Invoke(result.AsyncState);
                AlertContext.Dic_SMS_List.Add(((frmManualSendSMSAlert)result.AsyncState));

                //((frmPromptAlert)result.AsyncState).Show();
            }

        }


        private void BindContactGroups()
        {
            try
            {
                List<SMSContactGroup> checks = service.GetContactGroup().ToList();
                this.chklistDest.DataSource = checks;
                this.chklistDest.DisplayMember = "GroupName";
                this.chklistDest.ValueMember = "GroupCode";
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void BindBaseInfoOfAlertMessage()
        {
            txtAirPort.Text = smsAlertInfo.AirportFullName;
            txtAlertLevel.Text = smsAlertInfo.WarnLevelName;
            txtAlertTime.Text = smsAlertInfo.WarnTime.ToString();
            richtxtSMSContent.Text = smsAlertInfo.MessageBody;
        }

        void alertmassageservice_InsertSMSMsgModelCompleted(object sender, AsyncCompletedEventArgs e)
        {
            lock (locker)
            {
                AlertContext.Dic_Sms.Remove((string)e.UserState);
                AlertContext.Dic_Dispose_Sms.Remove((string)e.UserState);
            }
        }

        private void SetCheckedItems(List<string> checkedArr)
        {
            if (chklistDest.Items.Count > 0)
            {
                for (int i = 0; i < chklistDest.Items.Count; i++)
                {
                    chklistDest.SetItemChecked(i, false);
                }

                for (int i = 0; i < chklistDest.Items.Count; i++)
                {
                    if (checkedArr.Contains(((SMSContactGroup)chklistDest.Items[i]).GroupCode))
                    {
                        chklistDest.SetItemChecked(i, true);
                    }
                }
            }
        }

        private bool IsCheckedItems()
        {
            if (chklistDest.Items.Count > 0)
            {
                for (int i = 0; i < chklistDest.Items.Count; i++)
                {
                    if (chklistDest.GetItemChecked(i)) { return true; }
                }
            }
            return false;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (richtxtSMSContent.Text == string.Empty)
            {
                MessageBox.Show("短信内容不能为空！");
                richtxtSMSContent.Focus();
                return;
            }

            if (!IsCheckedItems())
            {
                MessageBox.Show("请选择发送对象！");
                return;
            }

            List<string> al = new List<string>();

            if (chklistDest.Items.Count > 0)
            {
                for (int i = 0; i <= chklistDest.Items.Count - 1; i++)
                {
                    if (chklistDest.GetItemChecked(i))
                    {
                        al.Add(((SMSContactGroup)(chklistDest.Items[i])).GroupCode);
                    }
                }
            }
            AlertContext.Dic_Dispose_Sms.Add(smsAlertInfo.SMSAlertID.ToString(), this);
            alertmassageservice.InsertSMSMsgModelAsync(smsAlertInfo.SMSAlertID.ToString(), al.ToArray(), richtxtSMSContent.Text, service.DASoapHeaderValue.UserId, smsAlertInfo.SMSAlertID.ToString());

            this.Close();
        }

        private void btnNoSend_Click(object sender, EventArgs e)
        {
            string[] companyCodes = new string[0];
            AlertContext.Dic_Dispose_Sms.Add(smsAlertInfo.SMSAlertID.ToString(), this);
            alertmassageservice.InsertSMSMsgModelAsync(smsAlertInfo.SMSAlertID.ToString(), companyCodes, richtxtSMSContent.Text, service.DASoapHeaderValue.UserId, smsAlertInfo.SMSAlertID.ToString());

            //SysGlobal.oldSMSAlertAllInfoList.Remove(smsAlertInfo);
            //AlertContext.Dic_Sms.Remove(smsAlertInfo.SMSAlertID.ToString());
            this.Close();
        }
    }
}
